package com.atguigu.springcloud.payment.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author lenovo
 * @version 1.0
 * @date 2020/11/18 14:57
 */
@Service
@Slf4j
public class PaymentService {

    public String getInfoOk(Long id){
        String s = "线程：" + Thread.currentThread().getName() + " ok id=[" + id + "]";
        log.info(s);
        return s;
    }


    @HystrixCommand(fallbackMethod = "getInfoTimeoutHandler" , commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds" , value = "3000")
    })
    public String getInfoTimeout(Long id){
        Integer seconds = 2 ;
//        int age = 10/0;
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String s = "线程：" + Thread.currentThread().getName() + " timeout id=[" + id + "] 耗时【" + seconds + "】秒";
        log.info(s);
        return s;
    }

    public String getInfoTimeoutHandler(Long id){
        String s = "线程：" + Thread.currentThread().getName() + " timeout id=[" + id + "] ，系统异常或者运行报错，超时了 /(ㄒoㄒ)/~~";
        log.error(s);
        return s;
    }


    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),// 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),// 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), //时问窗口威
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")
    })
    public String paymentCircuitBreaker(Long id) {
        if (id < 0) {
            throw new RuntimeException("*********** id 不能为负数");
        }
        UUID uuid = UUID.randomUUID();
        String s = "线程：" + Thread.currentThread().getName() + " paymentCircuitBreaker id=[" + id + "] 流水号【" + uuid + "】";
        log.info(s);
        return s;
    }

    public String paymentCircuitBreaker_fallback(Long id) {
        String s = "线程：" + Thread.currentThread().getName() + " timeout id=[" + id + "] ，系统异常或者运行报错，超时了 /(ㄒoㄒ)/~~";
        log.error(s);
        return s;
    }

}
